package runnables;

import log.Logger;
import net.rim.blackberry.api.browser.Browser;
import net.rim.device.api.i18n.ResourceBundle;
import net.rim.device.api.system.ApplicationDescriptor;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;
import strings.WebcampusResource;
import test.GradeAnalyzer;
import beans.Update;

public class VersionRunnable implements Runnable, WebcampusResource{

	// RESOURCES
	private static ResourceBundle resources = ResourceBundle.getBundle(BUNDLE_ID, BUNDLE_NAME);

	Update u=null;

	public VersionRunnable(){
	}

	public void run() {

		GradeAnalyzer ga = GradeAnalyzer.getInstance();
		try{
			// get current version
			String version = ApplicationDescriptor.currentApplicationDescriptor().getVersion();
			u = ga.getVersion(version);
			if (u==null){
				//TODO couldn't get version
				Logger.log("Couldn't get version");
			}
		} catch (Exception e){
			System.out.println("********************** error while getting version info from webservice");
		}

		//if everything is ok, open the following screen
		UiApplication.getUiApplication().invokeLater(new Runnable() {
			public void run() {
				handleUpdate(u);
			}
		});
	}
	
	public void handleUpdate(Update u){

		if (u!=null){
			if (u.getIsLatest().equals("true")){
				// nothing to do: continue 
			} else {
				if (u.getEsObligatoria().equals("true")){
					int answer = Dialog.ask(Dialog.D_YES_NO, 
							resources.getString(ALERT_MUST_UPDATE));
					if (answer== Dialog.YES){
						Browser.getDefaultSession().displayPage(u.getLinkUltimaVersion());
					} else {
						// cant continue, exit application
						System.exit(0);
					}

				} else {
					//may update
					int answer = Dialog.ask(Dialog.D_YES_NO, 
							resources.getString(ALERT_MAY_UPDATE));
					if (answer==Dialog.YES){
						Browser.getDefaultSession().displayPage(u.getLinkUltimaVersion());
					} else {
						// nothing to do: continue 
					}
				}
			}
		} else {
			//TODO display unknown error
		}

	}

}
